"use client";
import React from 'react';
import { Button, Drawer, Form, Input, InputNumber, Space, Statistic, Typography, notification, Divider, Modal, message } from 'antd';
import { runClassify } from '../lib/api';
import { useTaskSSE } from '../lib/useSSE';

const { Text } = Typography;

interface Props {
  open: boolean;
  onClose: () => void;
  initialTaskId?: number;
  onDone?: () => void;
}

export default function RunDrawer({ open, onClose, initialTaskId, onDone }: Props) {
  const [form] = Form.useForm();
  const [taskId, setTaskId] = React.useState<number | undefined>();
  const [submitting, setSubmitting] = React.useState(false);
  const { data, error, connecting } = useTaskSSE(taskId, { enabled: !!taskId });
  const [api, contextHolder] = notification.useNotification();
  const lastEventRef = React.useRef<number | null>(null);

  React.useEffect(() => {
    if (data) {
      lastEventRef.current = Date.now();
      if (data.status && ["SUCCEEDED", "FAILED", "CANCELLED"].includes(data.status)) {
        api.open({
          message: `任务 ${data.status}`,
          description: `Task ID ${taskId}`,
        });
        if (data.status === 'SUCCEEDED' && onDone) {
          try { onDone(); } catch {}
        }
      }
    }
  }, [data, api, taskId]);

  // Accept initial task id from parent to auto-subscribe progress
  React.useEffect(() => {
    if (initialTaskId && !taskId) {
      setTaskId(initialTaskId);
    }
  }, [initialTaskId, taskId]);

  const waitingHint = React.useMemo(() => {
    if (connecting) return '正在连接...';
    const last = lastEventRef.current;
    if (!last) return undefined;
    const diff = Date.now() - last;
    if (diff >= 10000) return '等待响应中';
    return undefined;
  }, [connecting, data]);

  const onSubmit = async () => {
    try {
      const values = await form.validateFields();
      await new Promise<void>((resolve, reject) => {
        let pwd = '';
        Modal.confirm({
          title: '请先输入密码',
          content: (
            <div>
              <p>该操作会调用大模型，请确认。</p>
              <Input.Password autoFocus placeholder="请输入密码" onChange={(e) => (pwd = e.target.value)} />
            </div>
          ),
          okText: '确认',
          cancelText: '取消',
          onOk: () => {
            if (pwd === '123456') return Promise.resolve().then(() => resolve());
            message.error('密码不正确');
            return Promise.reject();
          },
          onCancel: () => reject(new Error('CANCELLED')),
        });
      });
      setSubmitting(true);
      const res = await runClassify({
        batchSize: values.batchSize,
        maxConcurrency: values.maxConcurrency,
        taskVersion: values.taskVersion,
      });
      setTaskId(res.taskId);
      api.success({
        message: '任务已启动',
        description: `taskId=${res.taskId}, version=${res.version}`,
      });
    } catch (e: any) {
      if (e?.errorFields) return; // form error
      api.error({ message: '启动失败', description: e?.message || '未知错误' });
    } finally {
      setSubmitting(false);
    }
  };

  const onCopy = async () => {
    if (!taskId) return;
    try {
      await navigator.clipboard.writeText(String(taskId));
      api.success({ message: '已复制 taskId' });
    } catch {
      api.warning({ message: '复制失败，请手动选择复制' });
    }
  };

  const processed = data?.processed ?? 0;
  const success = data?.success ?? 0;
  const failed = data?.failed ?? 0;
  const total = data?.total ?? 0;
  const throughput = (data?.throughput as unknown as number) ?? 0;
  const etaSeconds = (data?.etaSeconds as unknown as number) ?? 0;
  const status = data?.status;

  return (
    <Drawer
      title="批量分类"
      placement="right"
      width={480}
      open={open}
      onClose={onClose}
      destroyOnClose
      extra={
        <Space>
          {taskId && <Button onClick={onCopy}>复制 taskId</Button>}
          <Button onClick={onClose}>关闭</Button>
        </Space>
      }
    >
      {contextHolder}
      <Form
        form={form}
        layout="vertical"
        initialValues={{ batchSize: 200, maxConcurrency: 4 }}
      >
        <Form.Item label="batchSize" name="batchSize" rules={[{ required: false }]}> 
          <InputNumber min={100} max={2000} step={100} style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item label="maxConcurrency" name="maxConcurrency" rules={[{ required: false }]}> 
          <InputNumber min={1} max={32} style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item label="taskVersion" name="taskVersion" rules={[{ required: false }]}> 
          <InputNumber min={1} style={{ width: '100%' }} placeholder="留空自动创建最新版" />
        </Form.Item>
        <Space>
          <Button type="primary" onClick={onSubmit} loading={submitting}>
            启动
          </Button>
          {taskId && <Text type="secondary">taskId: {taskId}</Text>}
        </Space>
      </Form>

      <Divider />

      <Space size={24} wrap>
        <Statistic title="Processed" value={processed} suffix={total ? ` / ${total}` : ''} />
        <Statistic title="Success" value={success} />
        <Statistic title="Failed" value={failed} />
        <Statistic title="Throughput" value={throughput} precision={2} suffix="/s" />
        <Statistic title="ETA" value={etaSeconds} suffix="s" />
        {status && <Statistic title="Status" value={status} />}
      </Space>

      {waitingHint && <div style={{ marginTop: 12 }}><Text type="secondary">{waitingHint}</Text></div>}
      {error && <div style={{ marginTop: 12 }}><Text type="danger">{error}</Text></div>}
    </Drawer>
  );
}
